import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

const useBookmarkStore = defineStore(
  'bookmark',
  () => {
    const bookmarks = ref([
      {
        id: 1,
        title: 'Google',
        url: 'https://www.google.com',
        categoryId: 'work'
      }
    ])

    const categories = ref([
      { key: 'all', label: '全部' },
      { key: 'work', label: '工作' },
      { key: 'study', label: '学习' },
      { key: 'life', label: '生活' }
    ])

    const selectedCategory = ref(['all'])
    const searchText = ref('')

    const filteredBookmarks = computed(() => {
      let result = bookmarks.value

      if (searchText.value) {
        result = result.filter((bookmark) => bookmark.title.toLowerCase().includes(searchText.value.toLowerCase()) || bookmark.url.toLowerCase().includes(searchText.value.toLowerCase()))
      }

      if (selectedCategory.value[0] !== 'all') {
        result = result.filter((bookmark) => bookmark.categoryId === selectedCategory.value[0])
      }

      return result
    })

    // Actions
    function addBookmark(bookmark) {
      bookmarks.value.push({
        id: Date.now(),
        ...bookmark
      })
    }

    function updateBookmark(id, updatedBookmark) {
      const index = bookmarks.value.findIndex((b) => b.id === id)
      if (index !== -1) {
        bookmarks.value[index] = { ...bookmarks.value[index], ...updatedBookmark }
      }
    }

    function deleteBookmark(id) {
      const index = bookmarks.value.findIndex((b) => b.id === id)
      if (index !== -1) {
        bookmarks.value.splice(index, 1)
      }
    }

    function addCategory(name) {
      categories.value.push({
        key: Date.now().toString(),
        label: name
      })
    }

    function deleteCategory(category) {
      // 找到要删除的分类索引
      const index = categories.value.findIndex((c) => c.key === category.key)
      if (index !== -1) {
        // 将该分类下的书签移动到默认分类
        bookmarks.value = bookmarks.value.map((bookmark) => {
          if (bookmark.categoryId === category.key) {
            return { ...bookmark, categoryId: 'all' }
          }
          return bookmark
        })
        // 删除分类
        categories.value.splice(index, 1)
        // 如果当前选中的是被删除的分类，切换到默认分类
        if (selectedCategory.value[0] === category.key) {
          selectedCategory.value = ['all']
        }
      }
    }

    return {
      bookmarks,
      categories,
      selectedCategory,
      searchText,
      filteredBookmarks,
      addBookmark,
      updateBookmark,
      deleteBookmark,
      addCategory,
      deleteCategory
    }
  },
  {
    persist: true
  }
)

export { useBookmarkStore }
export default useBookmarkStore
